<?php

/**
 * Created by JetBrains PhpStorm.
 * User: GMC
 * Date: 10/3/13
 * Time: 2:20 PM
 * To change this template use File | Settings | File Templates.
 */
class WidgetLatestUpdate extends CWidget {
    public $products;

    public function init() {
        $latest_update = Yii::app()->cache->get('latest_update');
//        if ($latest_update == null || count($latest_update) == 0) {
        $products = Product::model()->findAll(array(
            'select' => 'product_id, product_name, price, currency, image_id',
            'condition' => '(published  = 1 or status = 1) and image_id > 0',
            'order' => 't.product_id DESC',
            'limit' => 24
        ));

        $models = array();
        $result = array();
        $num = 1;
        $index = 0;
        foreach ($products as $key => $item) {
            array_push($result, array(
                'id' => $item->product_id,
                'name' => $item->product_name,
                'picture' => $item->image != null ? ($item->image->image_path) : Yii::app()->params['no-image'],
                'price' => $item->price,
                'currency' => $item->currency
            ));
            if ($num == 12 || $key == count($products) - 1) {
                $models[$index] = $result;
                $result = array();
                $index++;
                $num = 1;
            } else {
                $num++;
            }
        }

        Yii::app()->cache->set('latest_update', $models, 'latest_update_time');
        $latest_update = Yii::app()->cache->get('latest_update');
//        }
        $this->products = $latest_update;
    }

    public function run() {
        return CWidget::render('widgetLatestUpdate', array('model' => $this->products));
    }
}